﻿using TbShop.Business.Components;
using TbShop.Entity;
using TbShop.Entity.Bussinessentity;
using TbShop.Web.Helpers;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;

namespace TbShop.Web.Infrastructure.Tbk
{
    public class TBKHelper
    {
        #region 商品相关
        /// <summary>
        /// 获取商品列表，根据配置项判断从淘宝API获取还是从数据库获取
        /// </summary>
        /// <param name="adzoneId"></param>
        /// <param name="query"></param>
        /// <param name="category"></param>
        /// <param name="sort"></param>
        /// <param name="page_no"></param>
        /// <param name="page_size"></param>
        /// <returns></returns>
        public static TBKGoodsListModel GetTBKGoods(string query, string category, string sort, int page_no, int page_size)
        {
            ITopClient client = new DefaultTopClient(TBKConfig.ServerUrl, TBKConfig.AppKey, TBKConfig.AppSecret, "json");
            TbkDgItemCouponGetRequest req = new TbkDgItemCouponGetRequest();
            req.AdzoneId = TBKConfig.AdzoneId;
            req.Q = query == null ? "" : query;
            req.Cat = category;
            req.PageNo = page_no;
            req.PageSize = page_size;
            var res = client.Execute(req);
            IEnumerable<TBKGoodsDetailModel> resultData = null;
            if (res != null && res.Results != null)
            {
                resultData = DataMapperHelper.MapList<TBKGoodsDetailModel>(res.Results);
                foreach (var item in resultData)
                {
                    decimal finalPrice = 0;
                    decimal.TryParse(item.ZkFinalPrice, out finalPrice);
                    item.ResultPrice = finalPrice;
                    if (!string.IsNullOrEmpty(item.CouponInfo))
                    {
                        decimal price = 0;
                        var str = item.CouponInfo.Split('减');
                        if (str.Length > 1)
                        {
                            var priceStr = str[1].Substring(0, str[1].Length - 1);
                            decimal.TryParse(priceStr, out price);
                        }
                        item.TbkCouponPrice = price;
                        if (finalPrice > 0)
                            item.ResultPrice = finalPrice - price;
                        item.Password = GetTBKPassword(item.Title, item.CouponClickUrl);
                    }
                }
            }
            return new TBKGoodsListModel()
            {
                TotalResults = res.TotalResults,
                Results = resultData != null ? resultData.ToList() : null
            };
        }

        /// <summary>
        /// 通用物料搜索API（导购） 用于数据抓取
        /// </summary>
        /// <param name="adzoneId"></param>
        /// <param name="query"></param>
        /// <param name="category"></param>
        /// <param name="sort"></param>
        /// <param name="page_no"></param>
        /// <param name="page_size"></param>
        /// <returns></returns>
        public static TBKMaterialGoodsListModel GetTBKGoodsSearch(string query, string category, string sort, int page_no, int page_size)
        {
            ITopClient client = new DefaultTopClient(TBKConfig.ServerUrl, TBKConfig.AppKey, TBKConfig.AppSecret, "json");
            TbkDgMaterialOptionalRequest req = new TbkDgMaterialOptionalRequest();
            req.AdzoneId = TBKConfig.AdzoneId;
            req.Q = query == null ? "" : query;
            req.Cat = category;
            req.PageNo = page_no;
            req.PageSize = page_size;
            req.HasCoupon = true;
            req.StartTkRate = 500;
            req.EndTkRate = 10000;
            req.Sort = sort;
            TbkDgMaterialOptionalResponse res = client.Execute(req);
            IEnumerable<TBKGoodsDetailMaterialModel> resultData = null;
            if (res != null && res.ResultList != null)
            {
                resultData = DataMapperHelper.MapList<TBKGoodsDetailMaterialModel>(res.ResultList);
                foreach (var item in resultData)
                {
                    if (!string.IsNullOrEmpty(item.CouponInfo))
                    {
                        decimal price = 0;
                        var str = item.CouponInfo.Split('减');
                        if (str.Length > 1)
                        {
                            var priceStr = str[1].Substring(0, str[1].Length - 1);
                            decimal.TryParse(priceStr, out price);
                        }
                        item.TbkCouponPrice = price;
                    }
                }
            }
            return new TBKMaterialGoodsListModel()
            {
                TotalResults = res.TotalResults,
                Results = resultData != null ? resultData.ToList() : null
            };
        }

        #endregion

        /// <summary>
        /// taobao.tbk.tpwd.create (淘宝客淘口令)
        /// </summary>
        /// <param name="Text"></param>
        /// <param name="Url"></param>
        /// <returns></returns>
        public static string GetTBKPassword(string Text, string Url)
        {

            ITopClient client = new DefaultTopClient(TBKConfig.ServerUrl, TBKConfig.AppKey, TBKConfig.AppSecret, "json");
            TbkTpwdCreateRequest req = new TbkTpwdCreateRequest();
            req.Text = Text;
            req.Url = Url;
            var res = client.Execute(req);
            if (res != null && res.Data != null)
            {
                return res.Data.Model;
            }
            return "";
        }
    }
}